use apkaddtoast::addmod::addtaost::addtoask;
use apkaddtoast::apktool::{apktoolbuild, apktoold};
use apkaddtoast::tools::{apk_qian_min, xin_jian_qian_min};
use clap::Parser;
use dotenv::dotenv;
use std::env;
use std::fs::{self};
use std::process::Command;

/// 命令行输入简介
#[derive(Parser, Debug)]
#[command(version, about, long_about = None)]
struct Args {
    /// APK名称
    #[arg()]
    apkpath: String,
}

fn main() {
    dotenv().ok();
    let keystore_alias = String::from("debug");
    let mut keystore_name = String::new();
    let mut keystore_password = String::new();

    for (key, value) in env::vars() {
        if key == "JARSIGNER" && !checktools(value.clone()) {
            panic!("请检查 JARSIGNER 工具!!!")
        } else if key == "KEYSTORE" {
            println!("签名密钥 --> {}", value);
            match fs::metadata(value.clone()) {
                Ok(_) => println!("文件存在：{}", value),
                Err(_) => {
                    if xin_jian_qian_min(
                        keystore_alias.clone(),
                        value.clone(),
                        keystore_password.clone(),
                    ) {
                        println!("密钥生成完成!!!")
                    }
                }
            }
            keystore_name = value.clone();
        } else if key == "KEYSTOREPASSWORD" {
            println!("签名密钥密码 --> {}", value);
            keystore_password = value.clone();
        } else if key == "APKTOOL" && !checktools(value.clone()) {
            panic!("请检查 apktool 工具!!!")
        }
        // println!("{}= {}", key, value);
    }

    let args = Args::parse();
    apktoold(args.apkpath); //  反编译apk
    addtoask(); // 添加弹窗
    apktoolbuild(); // 编译成apk
    apk_qian_min(keystore_alias, keystore_name, keystore_password);
}

fn checktools(name: String) -> bool {
    // println!("检查工具链！");
    let out = Command::new("sh")
        .arg("-c")
        .arg(name)
        .output()
        .expect("sh exec error!");
    let output_str = String::from_utf8_lossy(&out.stdout);
    // println!("检查工具链? {:#?}", output_str.to_string());
    if output_str != "" {
        return true;
    }
    false
}
